<template>
  <div class="container-content">
    <div class="container-content-single">
      <div class="container-content-header">
        <el-form ref="searchForm" :inline="true" :model="searchForm" :size="size">
          <el-form-item prop="keyword">
            <el-input v-model="searchForm.keyword" :placeholder="$t('请输入关键词')" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="init">
              {{ $t('搜索') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="container-content-main">
        <div class="operation">
          <el-button v-has="'btn_add'" type="primary" icon="el-icon-plus" :size="size" @click="add">
            {{ $t('添加角色') }}
          </el-button>
          <el-button v-has="'btn_batch_delete'" type="danger" icon="el-icon-minus" :size="size" @click="batchDel"
            :disabled="sels.length < 1">
            {{ $t('批量删除') }}
          </el-button>
        </div>
        <el-table style="width: 100%;" :data="tableList" @selection-change="selsChange" fit border highlight-current-row :size="size">
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column prop="name" :label="$t('角色名称')" align="center" min-width="120" />
          <el-table-column prop="description" :label="$t('角色描述')" show-overflow-tooltip align="center" min-width="150" />
          <el-table-column prop="status" :label="$t('状态')" align="center" min-width="60">
            <template slot-scope="{row}">
              <el-tag size="small" :type="statusArr[row.status].type">{{ statusArr[row.status].label }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" fixed="right" align="center" min-width="120">
            <template slot-scope="{row}">
              <el-button v-has="'btn_edit'" v-if="!['user', 'admin'].includes(row.code)" type="text" :size="size" @click="edit(row)">
                {{ $t('编辑') }}
              </el-button>
              <el-button v-has="'btn_assign_user'" type="text" :size="size" @click="assignUser(row)" v-if="row.code !== 'user'">{{ $t('分配人员') }}</el-button>
              <el-button v-has="'btn_assign_menu'" type="text" :size="size" @click="assignMenu(row)" v-if="row.code !== 'admin'">{{ $t('分配权限') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.limit"
          @pagination="init" />
      </div>
    </div>

    <!-- 新增编辑人员弹框 -->
    <el-dialog class="role-dialog" :title="dialogEdit ? $t('编辑') : $t('新增')" :visible.sync="dialogShow"
      :close-on-click-modal="closeOnclickModal" @close="closeDialog">
      <el-form ref="dialogForm" :model="dialogForm" :size="size" label-width="120px">
        <el-form-item :label="$t('角色名称：')" :rules="rf_rules({required:true})" prop="name">
          <el-input v-model="dialogForm.name" :placeholder="$t('请输入角色名称')" clearable />
        </el-form-item>
        <el-form-item :label="$t('角色描述：')" prop="description">
          <el-input type="textarea" :rows="4" v-model="dialogForm.description"
            :placeholder="$t('请输入角色描述')" clearable />
        </el-form-item>
        <el-form-item :label="$t('状态：')" :rules="rf_rules({required:true})" prop="status">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :label="1">{{$t('启用')}}</el-radio>
            <el-radio :label="0">{{$t('禁用')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--

        <el-form-item :label="$t('权限选择')" :rules="rf_rules({required:true})" prop="menuBtnDtoList">

        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="closeDialog">{{ $t('取消') }}</el-button>
        <el-button type="primary" :size="size" @click="submit">{{ $t('确定') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog class="custom-form-dialog dialogAssignMenu" title="分配权限" :visible.sync="dialogAssignMenuShow"
               :close-on-click-modal="closeOnclickModal" @close="closeAssignMenuDialog" top="5vh">
      <el-tree ref="permissionTree" :data="permissionTree" node-key="id" :props="defaultProps" @check="selectChange"
               :highlight-current="true" show-checkbox>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="closeAssignMenuDialog">{{ $t('取消') }}</el-button>
        <el-button type="primary" :size="size" @click="submitAssignMenu">{{ $t('确定') }}</el-button>
      </span>
    </el-dialog>
    <UserOrgDialogSelect ref="UserOrgDialogSelect" :isDialogUserOrgShow.sync="isDialogUserOrgShow"
                         @choose="submitAssignUser"></UserOrgDialogSelect>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import api from '@/utils/api.js'
  import Pagination from '@/components/Pagination'
  import UserOrgDialogSelect from '@/components/DialogSelect/userOrganization'
  export default {
    name: '/businessManager/role',
    components: {
      Pagination,
      UserOrgDialogSelect
    },
    data () {
      return {
        searchForm: {
          stat: true,
          keyword: '',
          page: 1,
          limit: 10
        },
        tableList: [],
        total: 0,
        statusArr: [
          {
            label: this.$t('禁用'),
            type: 'danger'
          },
          {
            label: this.$t('启用'),
            type: ''
          }
        ],
        sels: [],
        dialogEdit: false,
        dialogShow: false,
        dialogForm: {
          id: '',
          name: '',
          status: 1,
          description: '',
        },
        assignUserForm: {
          id: ''
        },
        assignMenuForm: {
          id: '',
          menuBtnDtoList: []
        },
        dialogAssignMenuShow: false,
        isDialogUserOrgShow: false,
        permissionTree: [],
        defaultProps: {
          children: 'childNodes',
          label: 'text'
        }
      }
    },
    watch: {

    },
    computed: {
      ...mapGetters(['size', 'closeOnclickModal'])
    },
    mounted () {
      this.init()
    },

    methods: {
      selectChange (data, node) {
        this.assignMenuForm.menuBtnDtoList = node.halfCheckedNodes.slice().concat(node.checkedNodes.slice())
      },
      selectData (key, dataKey, data) {
        this.dialogForm[dataKey] = data[0]
        this.dialogForm[key] = data[0].map(item => {
          return item.id
        })
        this.$refs.dialogForm.validateField(key)
      },
      selsChange (data) {
        this.sels = data
      },
      // 新增
      add () {
        this.dialogEdit = false
        this.dialogShow = true
        delete this.dialogForm.id
      },
      // 编辑
      edit (row) {
        this.dialogEdit = true
        this.dialogShow = true
        api.getRoleDetail(row.id).then(res => {
          const data = res.data
          this.dialogForm.id = data.id
          this.dialogForm.name = data.name
          this.dialogForm.status = data.status
          this.dialogForm.description = data.description
        })
      },
      // 分配人员
      assignUser (row) {
        this.assignUserForm.id = row.id
        api.rolesGetAssignUser(row.id).then(res => {
          let arrs = res.data.map(item => {
            return Object.assign({}, {id: item.objectId, type: item.objectType, text: item.objectName})
          })
          this.$refs.UserOrgDialogSelect.setSelectedList(arrs)
        })
        this.isDialogUserOrgShow = true
      },
      submitAssignUser (selectList) {
        let arrs = selectList.map(item => {
          return Object.assign({}, {objectId: item.id, type: item.type})
        })
        api.rolesAssignUser(this.assignUserForm.id, arrs).then(res => {
          this.$messageTip('success')
        })
      },
      // 分配权限
      async assignMenu (row) {
        this.assignMenuForm.id = row.id
        this.dialogAssignMenuShow = true
        await this.getPermissionTree()
        api.rolesGetAssignMenu(row.id).then(res => {
          this.assignMenuForm.menuBtnDtoList = res.data.map(item => {
            return Object.assign({}, {id: item.objectId, type: item.objectType})
          })
          const permissionIds = res.data.map(item => item.objectId)
          this.setChecked(this.permissionTree, permissionIds)
        })
      },
      // 不在list里的设为false 不选中
      setChecked (list, permissionIds) {
        for (let i = 0; i < list.length; i++) {
          this.$refs['permissionTree'].setChecked(list[i].id, permissionIds.includes(list[i].id))
          console.log(permissionIds.includes(list.id))
          if (list[i].childNodes && list[i].childNodes.length > 0) {
            this.setChecked(list[i].childNodes, permissionIds)
          }
        }
      },
      submitAssignMenu () {
        let arr = this.assignMenuForm.menuBtnDtoList.map(item => {
          return Object.assign({}, {objectId: item.id, type: item.type})
        })
        api.rolesAssignMenu(this.assignMenuForm.id, arr).then(res => {
          this.$messageTip('success')
          this.closeAssignMenuDialog()
        })
      },
      // 保存角色
      submit () {
        this.validateSubmit('dialogForm').then(() => {
          const params = this.dialogForm
          api.saveOrUpdateRole(params).then(res => {
            this.$message.success(this.$t("操作成功"))
            this.closeDialog()
            this.init()
          })
        }).catch(() => {})
      },
      // 批量删除
      batchDel () {
        const ids = this.sels.map(item => item.id).join(',')
        this.delConfirm().then(() => {
          api.deleteRole(ids).then(res => {
            this.$message.success(this.$t('删除成功'))
            this.init()
          })
        })
      },
      // 获取角色列表
      init () {
        const params = this.searchForm
        api.getRoleList(params).then(res => {
          this.tableList = res.data.list
          this.total = res.data.count
        })
      },
      // 获取权限列表树
      getPermissionTree () {
        return new Promise(resolve => {
          if (this.permissionTree.length <= 0) {
            api.getPermissionTree().then(res => {
              this.permissionTree = res.data
              resolve(this.permissionTree)
            })
          } else {
            resolve(this.permissionTree)
          }
        })
      },
      // 关闭角色弹框
      closeDialog () {
        this.$refs["dialogForm"].resetFields()
        this.dialogShow = false
      },
      // 关闭角色选择弹框
      closeAssignMenuDialog () {
        this.dialogAssignMenuShow = false
      }
    }
  }
</script>

<style lang="scss">
  .role-dialog {
    .el-dialog {
      width: 32%;
      min-width: 500px;
    }
  }
  .dialogAssignMenu {
    .el-dialog {
      height: 80%;
      display: flex;
      flex-direction: column;
      .el-dialog__body {
        flex: 1;
        overflow-y: auto;
      }
    }
    .el-tree-node__content {
      position: relative;
    }
    .el-tree-node {
      overflow: hidden;
    }
    .el-tree-node>.el-tree-node__children {
      overflow: hidden;
    }
    .el-tree-node__content>label.el-checkbox {
      position: absolute;
      right: 0;
    }
  }
</style>
